<?php
namespace app\admin\validate;

use app\common\model\Lang;
use app\common\model\Worker;
use think\facade\Session;
use think\Validate;

class LoginValidate extends Validate
{
    /**
     * @var array 规则
     */
    protected $rule = [
        'user' => 'require',
        'passwd' => 'require|min:8',
        'lang' => 'require',
        'captcha' => 'require|captcha|checkLogin:passwd'
    ];

    /**
     * @var array 错误描述
     */
    protected $message = [
        'user.require' => '请填写账号',
        'passwd.require' => '请填写密码',
        'lang.require' => '请选择需要管理的语言',
        'captcha.require' => '请填写验证码',
        'captcha.captcha' => '验证码有误',
        'captcha.checkLogin' => '账号或者密码错误'
    ];

    /**
     * @var array 场景
     */
    protected $scene = [
        'login' => ['user','passwd','lang','captcha']
    ];

    /**
     * @param $value
     * @param $rule
     * @param $data
     */
    public function checkLogin($value, $rule, $data)
    {
        $worker = Worker::WithUser($data['user'])->find();

        if ( !$worker ) {
            return false;
        }

        if ( false === password_verify( $data['passwd'], $worker['passwd']) ) {
            return false;
        }

        $lang_id = Lang::where('tag', $data['lang'])->value('id');
        Session::set('admin.worker', [
            'id' => $worker->id,
            'username' => $worker->username,
            'depart_id' => $worker->depart_id
        ]);
        Session::set('admin.lang.id', $lang_id);
        Session::set('admin.lang.tag', $data['lang']);
        return true;
    }
}
